package com.shensi.adminCollect.controller.label;

import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.entity.SysDept;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.label.LabelRule;
import com.shensi.adminCollect.domain.label.LabelRuleDetail;
import com.shensi.adminCollect.domain.label.RequsetSysDept;
import com.shensi.adminCollect.service.label.ILabelRuleDetailService;
import com.shensi.adminCollect.service.label.ILabelRuleService;
import com.shensi.adminCollect.domain.system.SysEnterpriseUser;
import com.shensi.adminCollect.service.system.ISysDeptService;
import com.shensi.adminCollect.service.system.ISysEnterpriseUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;

/**
 * 标签规则
Controller
 *
 * @author qujia
 * @date 2021-06-15
 */
@RestController
@RequestMapping("/label/rule")
@Api(value = "LabelRuleController", description = "标签规则控制器")
public class LabelRuleController extends BaseController
{
    @Autowired
    private ILabelRuleService labelRuleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ILabelRuleDetailService labelRuleDetailService;

    @Autowired
    private ISysEnterpriseUserService sysEnterpriseUserService;


    /**
     * 查询标签规则列表
     */
    @GetMapping("/list")
    @ApiOperation("查询标签规则列表")
    public TableDataInfo list(LabelRule labelRule)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //labelRule.setStationId(currentUser.getUser().getDeptId());
        if( "0".equals(currentUser.getUser().getUserLevel())){
           return null;
        }
        labelRule.setEnterpriseId(currentUser.getUser().getEnterpriseId());
//        labelRule.setDelFlag("0");
        startPage();
        List<LabelRule> list = labelRuleService.selectLabelRuleList(labelRule);
        return getDataTable(list);
    }
    /**
     * 查询当前人员的标签信息
     */
    @GetMapping("/listByLogin")
    @ApiOperation("查询当前人员的标签信息")
    public TableDataInfo listByLogin()
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        LabelRule labelRule=new LabelRule();
        labelRule.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        labelRule.setDelFlag("0");
        List<LabelRule> list = labelRuleService.selectLabelRuleList(labelRule);
        return getDataTable(list);
    }
    /**
     * 查詢油站的所有標簽
     * @param labelRule
     * @return
     */
    @GetMapping("/labelList")
    @ApiOperation("查詢油站的所有標簽")
    public TableDataInfo labelList(LabelRule labelRule)
    {

        LoginUser currentUser = SecurityUtils.getLoginUser();
        if("0".equals(currentUser.getUser().getUserLevel())){
            return getTable(null);
        }
        labelRule.setEnterpriseId(currentUser.getUser().getEnterpriseId());
//        labelRule.setDelFlag("0");
        startPage();
        List<LabelRule> list = labelRuleService.selectLabelRuleList(labelRule);
        TableDataInfo rspData = getTable(list);

        return rspData;
    }


    /**
     * 导出标签规则列表
     */
    @GetMapping("/export")
    @ApiOperation("导出标签规则列表")
    public AjaxResult export(LabelRule labelRule)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        if("0".equals(currentUser.getUser().getUserLevel())){
            return AjaxResult.error("信息错误");
        }
        labelRule.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        List<LabelRule> list = labelRuleService.selectLabelRuleList(labelRule);
        ExcelUtil<LabelRule> util = new ExcelUtil<LabelRule>(LabelRule.class);
        return util.exportExcel(list, "rule");
    }

    /**
     * 获取标签规则详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation("获取标签规则详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(labelRuleService.selectLabelRuleById(id));
    }

    /**
     *标签功能是否开启,标签名
     */

    @GetMapping("/sysDeptDemoList")
    @ApiOperation("标签功能是否开启")
    public AjaxResult sysDeptDemoList()
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysEnterpriseUser sysEnterpriseUser=sysEnterpriseUserService.selectSysEnterpriseUserById(currentUser.getUser().getEnterpriseId());
        RequsetSysDept requsetSysDept = new RequsetSysDept();
        requsetSysDept.setEnterpriseId(sysEnterpriseUser.getEnterpriseId());
        requsetSysDept.setEnterpriseName(sysEnterpriseUser.getEnterpriseName());
        requsetSysDept.setLabelFlag(sysEnterpriseUser.getLabelFlag());
        LabelRule labelRule =new LabelRule();
        labelRule.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        labelRule.setDelFlag("0");
        List<LabelRule> list = labelRuleService.selectLabelRuleList(labelRule);
        requsetSysDept.setLabelArr(list);
        return AjaxResult.success(requsetSysDept);
    }

    @GetMapping("/selectLabelList")
    @ApiOperation("获取标签规则列表")
    public AjaxResult selectLabelList()
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysDept dept = deptService.selectDeptById(currentUser.getUser().getDeptId());
        RequsetSysDept requsetSysDept = new RequsetSysDept();
        BeanUtils.copyProperties(dept,requsetSysDept);
        if(requsetSysDept!=null && requsetSysDept.getLabelFlag()!=null && requsetSysDept.getLabelFlag().equals("1")){
            LabelRule labelRule =new LabelRule();
            labelRule.setStationId(currentUser.getUser().getDeptId());
            labelRule.setDelFlag("0");
            startPage();
            List<LabelRule> list = labelRuleService.selectLabelRuleList(labelRule);
            if(list!=null && list.size()>0){
                for(LabelRule rule:list){
                    LabelRuleDetail detail =new LabelRuleDetail();
                    detail.setParentId(rule.getId());
                    detail.setDelFlag("0");
                    List<LabelRuleDetail> labelRuleDetailList = labelRuleDetailService.selectLabelRuleDetailList(detail);
                    if(labelRuleDetailList!=null && labelRuleDetailList.size()>0){
                        rule.setLabelRuleDetailList(labelRuleDetailList);
                    }
                }
            }
            requsetSysDept.setLabelArr(list);
        }
        return AjaxResult.success(requsetSysDept);
    }
    @PostMapping("/addlabel")
    @Transactional
    @ApiOperation("增加标签规则")
    public AjaxResult addlabel(@RequestBody RequsetSysDept requsetSysDept)
    {
        int i =0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //根据demo获取添加数据
        if(requsetSysDept!=null){
            SysEnterpriseUser sysEnterpriseUser=new SysEnterpriseUser();
            sysEnterpriseUser.setEnterpriseId(currentUser.getUser().getEnterpriseId());
            sysEnterpriseUser.setLabelFlag(requsetSysDept.getLabelFlag());
            i =  sysEnterpriseUserService.updateSysEnterpriseUser(sysEnterpriseUser);
            if(requsetSysDept.getLabelArr()!=null && requsetSysDept.getLabelArr().size()>0){
                for(LabelRule labelRule : requsetSysDept.getLabelArr()) {
                    labelRule.setEnterpriseId(currentUser.getUser().getEnterpriseId());
                    if(labelRule.getId()!=null){
                        labelRule.setUpdateBy(currentUser.getUser().getUserId()+"");
                        i=labelRuleService.updateLabelRule(labelRule);
                    }else{
                        labelRule.setStationId(currentUser.getUser().getDeptId());
                        labelRule.setCreateBy(currentUser.getUser().getUserId()+"");
                        labelRule.setDelFlag("0");
                        i=labelRuleService.insertLabelRule(labelRule);
                    }
                }
            }
            if(requsetSysDept.getDelArr()!=null &&requsetSysDept.getDelArr().size()>0){
                List<Integer> idlist =requsetSysDept.getDelArr();
                //Integer[] ints = idlist.toArray(new Integer[0]);
                for(Integer ids :idlist){
                    LabelRule labelRule =new LabelRule();
                    labelRule.setId(ids);
                    labelRule.setDelFlag("1");
                    labelRule.setUpdateBy(currentUser.getUser().getUserId()+"");
                    labelRuleService.updateLabelRule(labelRule);
                }
            }
        }
        return toAjax(i);
    }


    @PostMapping("/addlabelrule")
    @ApiOperation("新增标签")
    public AjaxResult addlabelrule(@RequestBody LabelRule labelRule)
    {
        int i =0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        labelRule.setCreateBy(currentUser.getUser().getUserId()+"");
        //根据demo获取添加数据
        LabelRule labelRuleForQ = new LabelRule();
        labelRuleForQ.setLabelName(labelRule.getLabelName());
        labelRuleForQ.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        List<LabelRule> labelRuleForQList=  labelRuleService.selectLabelRuleListForQ(labelRuleForQ);
        if (labelRuleForQList == null || labelRuleForQList.isEmpty()) {
            try {
                labelRule.setDelFlag("1");//默认为不启用
                i=labelRuleService.insertLabelRule(labelRule);
                return toAjax(i);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            return AjaxResult.error("标签名重复");
        }
        return toAjax(i);
    }

    /**
     * 修改标签规则
     */
    @PutMapping
    @ApiOperation("修改标签规则")
    public AjaxResult edit(@RequestBody LabelRule labelRule)
    {
        if(labelRule.getCreateTime()==null&&labelRule.getDelFlag().equals("1")){
            //关闭渠道
            Integer id = labelRule.getId();
            Integer count=labelRuleService.countInReviewAudit(id);
            if(count>0){
                return AjaxResult.error("存在审核中的用户，对应渠道不允许停用");
            }
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        labelRule.setUpdateBy(currentUser.getUser().getUserId()+"");

        LabelRule labelRuleForQ = new LabelRule();
        labelRuleForQ.setLabelName(labelRule.getLabelName());
        List<LabelRule> labelRuleForQList=  labelRuleService.selectLabelRuleListForQ(labelRuleForQ);
        if (labelRuleForQList == null || labelRuleForQList.isEmpty()) {
            return toAjax(labelRuleService.updateLabelRule(labelRule));
        }else{
           for(LabelRule labelrulelist:labelRuleForQList){
               if(labelrulelist.getId().equals(labelRule.getId())){
                   return toAjax(labelRuleService.updateLabelRule(labelRule));
               }
           }
            return AjaxResult.error("标签名重复");
        }


    }

    /**
     * 删除标签规则
     */
    @DeleteMapping("/{ids}")
    @ApiOperation("删除标签规则")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {

        return toAjax(labelRuleService.deleteLabelRuleByIds(ids));
    }

    @ExceptionHandler(CustomException.class)
    public AjaxResult handleUserNotFoundException(CustomException ex) {
        if(ex.getMessage().contains("存在未处理的渠道审核，渠道不能删除")){
            return AjaxResult.error("存在未处理的渠道审核，渠道不能删除");
        }else{
            return AjaxResult.error(ex.getMessage());
        }

    }
}
